package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.Mediatype;
import com.qianniu.napi.admin.entity.penum.Rtype;
import com.qianniu.napi.admin.service.IBannerService;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.admin.service.IResourceService;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.admin.service.akka.StoreActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.*;
import org.apache.ibatis.annotations.Param;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2018-06-15
 */
@RestController
public class BannerController {

    private static final Logger logger = LoggerFactory.getLogger(BannerController.class);

    @Autowired
    private IBannerService bannerService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IResourceService resourceService;

//    @RequestMapping("/banner/list")
//    @ResponseBody
//    public Page<Banner> list(@RequestParam(value="ptype",required = false)String ptype) {
//        if(Strings.isNullOrEmpty(ptype)){
//            ptype = "1";
//        }
//        Page<Banner> page =new Page<Banner>(0, 6);
//        Wrapper wrapper = new EntityWrapper<Banner>().eq("state", "1").eq("ptype", ptype);
//        Page<Banner> list = bannerService.selectPage (page,wrapper);
//        return list;
//    }

    @RequestMapping(value = "/upload/file", method = RequestMethod.POST)
    @ResponseBody
    public JsonDO uploadLogo(@RequestParam(value = "mfile", required = true) MultipartFile mfile,
                             @RequestParam(value = "t", required = false) String t,
                             @RequestParam(value = "type", required = true) String type) {
        JsonDO json = new JsonDO();
        if (mfile != null) {

            String fileName = mfile.getOriginalFilename();
            logger.debug(">>>mediafile=" + fileName);

            String rfilename = fileName.substring(0, fileName.lastIndexOf("."));
            if (rfilename.length() > 16) rfilename = rfilename.substring(0, 16);
            String extname = fileName.substring(fileName.lastIndexOf(".") + 1);
            String[] ts = type.split("_");
            String tyth = ts.length == 2 ? ts[0] + "/" + ts[1] + "/" : ts[0] + "/";
            String dirpath = Constants.IMG_UPLOAD_PATH + "ungroup/" + tyth;

            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Date date = new Date();
//            String filename = EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname;
            String newfname = "";
            try {
                newfname = StringUtil.isContainChinese(rfilename) ? PinyinHelper.convertToPinyinString(rfilename, "", PinyinFormat.WITHOUT_TONE) : rfilename;
                newfname = newfname.replaceAll(" ", "").replaceAll("、", "").replaceAll("-", "");
                logger.debug(">>>after convertToPinyinString newfname=" + newfname);
            } catch (Exception e) {
                logger.error(">>>tpinyin error", e);
            }

            newfname = Strings.isNullOrEmpty(newfname) ? EncryptUtil.md5(date.getTime() + fileName).substring(0, 16) : newfname;
            if (newfname.length() > 16) newfname = newfname.substring(0, 16);

//            File file = new File(dirpath + EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname);// 保持原有文件格式
            File file = new File(dirpath + newfname + "." + extname);// 保持原有文件格式
            if (file.exists()) {
                newfname = EncryptUtil.md5(date.getTime() + fileName).substring(0, 16);
                file = new File(dirpath + newfname + "." + extname);
            }
            logger.debug(">>>targetFile getAbsolutePath=" + file.getAbsolutePath());
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            //保存
            try {
                file.createNewFile();
                logger.debug(">>>start to FileOutputStream");

                outputStream = new FileOutputStream(file);
                inputStream = mfile.getInputStream();
                byte temp[] = new byte[1024];
                int size = -1;
                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                    logger.info("File load size=" + size);
                    outputStream.write(temp, 0, size);
                }

                logger.info("File load success.");
            } catch (IOException e) {
                logger.warn("File load fail.", e);
            } finally {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("IO close error", e);
                }
            }

            String imgurl = Constants.IMG_UPLOAD_HOST + "ungroup/" + tyth + file.getName();
            json.setData(imgurl);
        }

        json.setMsg("ok");
        return json;
    }

    // ************* bellow is mechant interface *********

    @RequestMapping(value = "/api/upload/file", method = RequestMethod.POST)
    @ResponseBody
    public JsonDO uploadFile(@RequestParam(value = "mfile", required = true) MultipartFile mfile,
                             @RequestParam(value = "yasuo", required = false) Integer yasuo,
                             @RequestParam(value = "type", required = true) String type,
                             @RequestParam(value = "f", required = true) String f) {
        JsonDO json = new JsonDO();
        if (mfile != null) {

            String fileName = mfile.getOriginalFilename();
            logger.debug(">>>mediafile=" + fileName);
            Long mid = ObjectUtil.getMid();
            Long mpid = ObjectUtil.getMpid();
            Long sid = ObjectUtil.getSid();

            MerchantApp mapp = redisService.getMApp();
            String rfilename = fileName.substring(0, fileName.lastIndexOf("."));
            if (rfilename.length() > 16) rfilename = rfilename.substring(0, 16);
            String extname = fileName.substring(fileName.lastIndexOf(".") + 1);
            String[] ts = type.split("_");
            String tyth = ts.length == 2 ? ts[0] + "/" + ts[1] + "/" : ts[0] + "/";
            String mcode = mapp == null ? "ungroup" : mapp.getMcode() + "/" + mapp.getMpcode();
            String uppath = mapp.getIscdn() == 1 ? Constants.IMG_UPLOAD_PATH + "0cdn/" : Constants.IMG_UPLOAD_PATH;
            String dirpath = uppath + mcode + "/" + tyth;
            logger.info("======/api/upload/file dirpath=" + dirpath);

            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Date date = new Date();
//            String filename = EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname;
            String newfname = "";
            try {
                newfname = StringUtil.isContainChinese(rfilename) ? PinyinHelper.convertToPinyinString(rfilename, "", PinyinFormat.WITHOUT_TONE) : rfilename;
                newfname = newfname.replaceAll(" ", "").replaceAll("、", "").replaceAll("-", "");
                logger.debug(">>>after convertToPinyinString newfname=" + newfname);
            } catch (Exception e) {
                logger.error(">>>tpinyin error", e);
            }

            newfname = Strings.isNullOrEmpty(newfname) ? EncryptUtil.md5(date.getTime() + fileName).substring(0, 16) : newfname;
            if (newfname.length() > 16) newfname = newfname.substring(0, 16);

//            File file = new File(dirpath + EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname);// 保持原有文件格式
            File file = new File(dirpath + newfname + "." + extname);// 保持原有文件格式
            if (file.exists()) {
                newfname = EncryptUtil.md5(date.getTime() + fileName).substring(0, 16);
                file = new File(dirpath + newfname + "." + extname);
            }
            logger.debug(">>>targetFile getAbsolutePath=" + file.getAbsolutePath());
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            int cout = 0;
            //保存
            try {
                file.createNewFile();
                logger.debug(">>>start to FileOutputStream");

                outputStream = new FileOutputStream(file);
                inputStream = mfile.getInputStream();
                byte temp[] = new byte[1024];
                int size = -1;

                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                    logger.info("File load size=" + size);
                    outputStream.write(temp, 0, size);
                    cout++;
                }

                logger.info("File load success.");
            } catch (IOException e) {
                logger.warn("File load fail.", e);
            } finally {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("IO close error", e);
                }
            }
            logger.info("-----------------------------------uploadfile size cout=" + cout);
            logger.info("-----------------------------------uploadfile yasuo=" + yasuo);
            // 默认压缩1M大小的图
            if (cout > 1000 && (yasuo == null || yasuo.intValue() != -1)) {
                logger.info("-----------------------------------start yasuo uploadfile");
                PictureUtil.yasuo(file.getAbsolutePath(), null, null);
            }
            String host = mapp.getIscdn().intValue() == 1 ?
                    Constants.IMG_UPLOAD_HOST.replace("//img.", "//imgcdn.") : Constants.IMG_UPLOAD_HOST;
            String imgurl = host + mcode + "/" + tyth + file.getName();

            json.setData(imgurl);
            json.setMsg("ok");

            //type+pic+mid+mpid+ sid + mediatype+ tbtype+ fieldname
            if (Strings.isNullOrEmpty(f)) f = "pic";
            AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                    .tell("uploadfile" + "@" + imgurl + "@" + mid + "@" + mpid + "@" + sid
                            + "@" + Mediatype.picture.getVal() + "@" + type + "@" + f, ActorRef.noSender());

        }

        return json;
    }

    @RequestMapping(value = "/api/upload/vfile", method = RequestMethod.POST)
    @ResponseBody
    public Jinfo uploadVFile(@RequestParam(value = "mfile", required = true) MultipartFile mfile,
                             @RequestParam(value = "type", required = true) String type
    ) {
        Jinfo json = new Jinfo();
        if (mfile != null) {

            String fileName = mfile.getOriginalFilename();
            logger.debug(">>>mediafile=" + fileName);

            MerchantApp mapp = redisService.getMApp();
            String rfilename = fileName.substring(0, fileName.lastIndexOf("."));
            if (rfilename.length() > 16) rfilename = rfilename.substring(0, 16);
            String extname = fileName.substring(fileName.lastIndexOf(".") + 1);
            String[] ts = type.split("_");
            String tyth = ts.length == 2 ? ts[0] + "/" + ts[1] + "/" : ts[0] + "/";
            String mcode = mapp == null ? "ungroup" : mapp.getMcode() + "/" + mapp.getMpcode();
            String uppath = mapp.getIscdn() == 1 ? Constants.IMG_UPLOAD_PATH + "0cdn/" : Constants.IMG_UPLOAD_PATH;
            String dirpath = uppath + mcode + "/v/" + tyth;
            logger.info("======/api/upload/file dirpath=" + dirpath);

            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Date date = new Date();
            String newfname = "";
            try {
                newfname = StringUtil.isContainChinese(rfilename) ? PinyinHelper.convertToPinyinString(rfilename, "", PinyinFormat.WITHOUT_TONE) : rfilename;
                newfname = newfname.replaceAll(" ", "").replaceAll("、", "").replaceAll("-", "");
                logger.debug(">>>after convertToPinyinString newfname=" + newfname);
            } catch (Exception e) {
                logger.error(">>>tpinyin error", e);
            }

            newfname = Strings.isNullOrEmpty(newfname) ? EncryptUtil.md5(date.getTime() + fileName).substring(0, 16) : newfname;
            if (newfname.length() > 16) newfname = newfname.substring(0, 16);
            String path = dirpath + newfname + "." + extname;
            File file = new File(path);//保持原有文件格式

            if (file.exists()) {
                newfname = EncryptUtil.md5(date.getTime() + fileName).substring(0, 16);
                file = new File(dirpath + newfname + "." + extname);
            }
            logger.debug(">>>targetFile getAbsolutePath=" + file.getAbsolutePath());
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            int cout = 0;
            long allsize = 0;

            //保存
            try {
                file.createNewFile();
                logger.debug("------------------------------start to FileOutputStream");
                outputStream = new FileOutputStream(file);
                inputStream = mfile.getInputStream();
                byte temp[] = new byte[1024];
                int size = -1;

                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                    logger.info("File load size=" + size);
                    outputStream.write(temp, 0, size);
                    allsize += size;
                    cout++;
                }

                logger.info("File load success.");
            } catch (IOException e) {
                logger.warn("File load fail.", e);
            } finally {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("IO close error", e);
                }
            }

            //如果大于10M，则删除
            if (mapp.getMid() != 1 && mapp.getMid() != 20 && allsize > 1024 * 1024 * 10) {
                File dfile = new File(path);
                dfile.delete();

                json.setCode(1);
                json.setMsg("上传视频文件不能大于10M");
                return json;
            }
            logger.info("-----------------------------------uploadfile size cout=" + cout);

            String host = mapp.getIscdn().intValue() == 1 ?
                    Constants.IMG_UPLOAD_HOST.replace("//img.", "//imgcdn.") :
                    Constants.IMG_UPLOAD_HOST;

            String vurl = host + mcode + "/v/" + tyth + file.getName();

            Resource resource = new Resource();
            resource.setMid(ObjectUtil.getMid());
            resource.setMpid(ObjectUtil.getMpid());
            resource.setSid(ObjectUtil.getSid());
            resource.setUid(ObjectUtil.getUid());

            resource.setName(file.getName());
            resource.setPic(vurl);
            resource.setSize(allsize);
            resource.setRtype(Rtype.vedio.getVal());
            resource.setCreatetime(new Date());
            resource.setIsmedia(-1);
            resource.setMediatype(Mediatype.video.getVal());
            resource.setIsuse(-1);

            //读取缩略图+时长
            try {
                String thumburl = host + mcode + "/v/" + tyth + file.getName().replace("." + extname, ".jpg");
                resource.setThumb(thumburl);
                Long duration = VideoUtil.getDuration(path);

                resource.setDuration(duration);
                if (mapp.getMid() != 1 && mapp.getMid() != 20 && resource.getDuration() > 45) {

                    File dfile2 = new File(path);
                    dfile2.delete();

                    json.setCode(1);
                    json.setMsg("上传视频文件时长不能超过45秒");
                    return json;
                }

                JSONObject jo = VideoUtil.fetchPic(path, path.replace("." + extname, ".jpg"));
                resource.setMheight(jo.getInteger("mheight"));
                resource.setPixel(jo.getInteger("owidth") + "x" + jo.getInteger("oheight"));

            } catch (Exception e) {
                logger.error("----------------VideoUtil process error", e);
            }

            resource.insert();
            json.setData(vurl);
            json.setExtra(resource);
        }

        json.setMsg("ok");
        return json;
    }

    @RequestMapping("/api/banner/list")
    @ResponseBody
    public JsonDO bannerList(HttpServletRequest req) {
        JsonDO json = new JsonDO();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("mid", req.getSession().getAttribute("mid"));
        map.put("state", 1);
        List<Banner> list = bannerService.selectByMap(map);
        json.setData(list);
        return json;
    }

    @RequestMapping("/api/banner/add")
    @ResponseBody
    public JsonDO addrAdd(Banner bean,
                          BindingResult bindingResult) {
        JsonDO json = new JsonDO();
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            json.setMsg("There are errors! " + bindingResult);
            json.setCode(400);
            return json;
        }
        bean.setCreatetime(new Date());
        bean.insert();
        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Banner@" + bean.getId() + "@insert", ActorRef.noSender());

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_BANNER_MODIFY + "@" + bean.getId(), ActorRef.noSender());
        return json;
    }

    @RequestMapping("/api/banner/modify")
    @ResponseBody
    public JsonDO addrUpdate(@Valid Banner bean,
                             BindingResult bindingResult) {
        JsonDO json = new JsonDO();
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            json.setMsg("There are errors! " + bindingResult);
            json.setCode(400);
            return json;
        }
        bean.setModifytime(new Date());
        bean.updateById();

        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Banner@" + bean.getId() + "@update", ActorRef.noSender());

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_BANNER_MODIFY + "@" + bean.getId(), ActorRef.noSender());
        return json;
    }

    @RequestMapping("/api/banner/detail")
    @ResponseBody
    public JsonDO getBannerDetailById(@Param("token") String token,
                                      @Param("id") long id
    ) {
        JsonDO json = new JsonDO();
        Banner banner = bannerService.selectById(id);
        json.setData(banner);
        return json;
    }

    @RequestMapping("/api/banner/getHyads")
    @ResponseBody
    public Jinfo getHyads(Long hyid) {
        Jinfo info = new Jinfo();

        List<Banner> banners = bannerService.selectList(new EntityWrapper<Banner>().eq("hyid", hyid)
                .eq("mpid", ObjectUtil.getMpid())
                .orderBy("sort", true)
        );
        info.setInfo(banners);
        return info;
    }
}
